package org.skipper.common;

import org.skipper.common.constant.CodeInterface;
import org.skipper.common.constant.CommonCodeEnum;

/**
 * 此类是作为SpringMVC Controller返回结果的基类
 * 可以直接作为返回Model返回
 *
 * @author he.wang
 * @since 1.0.0
 */
public class Result<T> extends Response {

    private static final long serialVersionUID = 8812516627246681089L;

    /**
     * 返回数据
     */
    private T data;

    public T getData() {
        return data;
    }

    public void setData(T data) {
        this.data = data;
    }

    public static <T> Result<T> createErrorMsg(String code, String message, T data) {
        Result<T> result = new Result<>();
        result.setCode(code);
        result.setMessage(message);
        result.setData(data);
        return result;
    }

    public static <T> Result<T> createErrorMsg(CodeInterface code) {
        Result<T> result = new Result<>();
        result.setCode(code.getCode());
        result.setMessage(code.getMessage());
        return result;
    }

    //带数据的错误返回
    public static <T> Result<T> createErrorMsg(CodeInterface code, T data) {
        Result<T> result = new Result<>();
        result.setCode(code.getCode());
        result.setMessage(code.getMessage());
        result.setData(data);
        return result;
    }

    public static <T> Result<T> createSuccessMsg(T data) {
        Result<T> result = new Result<>();
        result.setCode(CommonCodeEnum.SUCCESS.getCode());
        result.setMessage(CommonCodeEnum.SUCCESS.getMessage());
        result.setData(data);
        return result;
    }

    public static <T> Result<T> createSuccessMsg() {
        Result<T> result = new Result<>();
        result.setCode(CommonCodeEnum.SUCCESS.getCode());
        result.setMessage(CommonCodeEnum.SUCCESS.getMessage());
        return result;
    }

    public static boolean isResultSuccess(Result result) {
        return result != null && CommonCodeEnum.SUCCESS.getCode().equals(result.getCode());
    }

    public static boolean isResultNotSuccess(Result result) {
        return !isResultSuccess(result);
    }

    public static boolean isDataNotNull(Result result) {
        return isResultSuccess(result) && result.getData() != null;
    }

    public static boolean isModelNull(Result result) {
        return !isDataNotNull(result);
    }


    @Override
    public String toString() {
        return "Result{" +
                "response =" + super.toString() +
                ", data=" + data +
                '}';
    }
}
